package com.example.startscreen;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ThreadFactory;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.AssetManager;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RotateDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

/*
 * Object of this class expects that calling activity pass several arguments,
 * through the extras.setXXX, extras.getXXX way:
 * 1. ArrayList<String>, under the keyname: imageNamesArr, what means array of image file names for location that should be displayd
 * 2. ArrayList<String>, under the keyname: imageUrlsArr, what means array of image URL names (where from the image was downloaded)
 * 3. String, under the keyname: locDescription, i.e. file name of XML file, with description about location
 * 4. Strings under the keynames: url, phoneNumber, name, city 
 */
public class LocationInfoActivity extends Activity {
	MyThread myThread; // thread to support gallery slide-show
	ImageAdapter myAdapter; // reference to adapter
	Gallery myGallery;
	CustomGallery g;
	MyExtendedLocation curItem;

	ArrayList<ImageGalleryInfo> locationFilenameArrList = new ArrayList<ImageGalleryInfo>();

	private String locDescription; // location description info (MNE or ENG text)
	private String phoneNumber = "";
	private String url = "";
	private String name = "";
	private String city = "";
	final Context context = this;

	int nextImageId = 0; // index of next image that should be displayed 

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.gallery);

		// ----------- dodato za poziv iz main klase -------------------
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			ArrayList<String> imageNamesArr = new ArrayList<String>();
			imageNamesArr = extras.getStringArrayList("imageNamesArr");
			ArrayList<String> imageUrlsArr = new ArrayList<String>();
			imageUrlsArr = extras.getStringArrayList("imageUrlsArr");

			locDescription = extras.getString("locDescription");
			Log.i("LocationInfoActivity - OnCreate", "locDescription: " + locDescription);

			url = extras.getString("url");
			phoneNumber = extras.getString("phoneNumber");
			name = extras.getString("name");
			city = extras.getString("city");

			for (int i=0; i < imageNamesArr.size(); i++) {
				ImageGalleryInfo igi = new ImageGalleryInfo(imageNamesArr.get(i), imageUrlsArr.get(i));
				locationFilenameArrList.add(igi);
			}

		}

		// -------------------------------------------------------------

		TableLayout tl = (TableLayout) findViewById(R.id.TableLayout1);
		
		
		// za odabir slike za pozadinu table LAYOUTA
		
		if (city.equalsIgnoreCase("bar") || city.equalsIgnoreCase("ulcinj") || city.equalsIgnoreCase("budva") ||  city.equalsIgnoreCase("kotor") || 
			city.equalsIgnoreCase("herceg novi") ||  city.equalsIgnoreCase("tivat")){
			tl.setBackgroundResource(R.drawable.more2);
		}
		if (city.equalsIgnoreCase("plužine") || city.equalsIgnoreCase("žabljak") || city.equalsIgnoreCase("pljevlja") ||  city.equalsIgnoreCase("šavnik") || 
				city.equalsIgnoreCase("kolašin") ||  city.equalsIgnoreCase("mojkovac") ||  city.equalsIgnoreCase("bijelo polje") ||  city.equalsIgnoreCase("andrijevica") 
				||  city.equalsIgnoreCase("berane") ||  city.equalsIgnoreCase("plav") ||  city.equalsIgnoreCase("rožaje") ){
			
			tl.setBackgroundResource(R.drawable.compasspicture);
		}
		if(city.equalsIgnoreCase("podgorica") || city.equalsIgnoreCase("danilovgrad") || city.equalsIgnoreCase("nikšić") ||  city.equalsIgnoreCase("cetinje")){
			tl.setBackgroundResource(R.drawable.compasspicture);
		}
		
		myAdapter = new ImageAdapter(this);

		g = (CustomGallery) findViewById(R.id.gallery1);
		g.setAdapter(myAdapter);
		g.setBackgroundColor(Color.TRANSPARENT);

		g.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				drawLargeImage(getDrawable(locationFilenameArrList.get(g.getSelectedItemPosition()).imageName), g.getSelectedItemPosition());
			}

		});

		// ZA CALL BUtton
		ImageButton callButton = (ImageButton) findViewById(R.id.callButton);
		ImageButton urlButton = (ImageButton) findViewById(R.id.urlButton);
		ImageButton directionButton = (ImageButton) findViewById(R.id.directionButton);
		ImageButton direction1Button = (ImageButton) findViewById(R.id.direction1Button);

		if (phoneNumber.equals("NA") || phoneNumber.equals(null) || phoneNumber.equals("")) {
			callButton.setEnabled(false);
			Log.i("LocationInfoActivity - OnCreate - disabled call button", "Phone: " + phoneNumber);
		}
		if (url.equals(null) || url.equals("")) {
			urlButton.setEnabled(false);
			Log.i("LocationInfoActivity - OnCreate - disabled url button", "Url: " + url);
		}

		urlButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setData(Uri.parse(url));
				startActivity(i);
			}
		});

		callButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent i = new Intent(Intent.ACTION_DIAL);
				String p = "tel:" + phoneNumber;
				i.setData(Uri.parse(p));
				startActivity(i);
			}
		});

		directionButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// open dialog and ask for destination 
				showDirectionDialog();
			}
		});

		direction1Button.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
        		Intent in = new Intent();
        		in.putExtra("destLocation", "NA");
        		in.putExtra("drawRouteToMyLocation", (int)1);
        		setResult(Activity.RESULT_OK, in);
        		finish();
			}
		});

		// Display title (location, small text)
		TextView textTitle = (TextView) findViewById(R.id.textView1);
		textTitle.setText(name);

		// Display location info in textview. 
		TextView tv = (TextView) findViewById(R.id.textView2);
		tv.setText((CharSequence) locDescription + "\r\n");
		tv.setTextColor(Color.BLACK);
		tv.setMovementMethod(LinkMovementMethod.getInstance());
		tv.invalidate();

	}

	public void drawLargeImage(Drawable d, int imageId) {

		// stop gallery movement, while displaying large image
		g.setRunning(false);

		final Dialog dialog = new Dialog(context);
		// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
		dialog.setContentView(R.layout.gallery_imageview);
		// display dialog title
		dialog.setTitle(name);

		// display image URL
		String imageUrlText = "";
		TextView imageUrl = (TextView) dialog.findViewById(R.id.image_url);
		// check imageId, not to get exception!!!
		if (imageId >= 0 && imageId < locationFilenameArrList.size()) {
			if ((!locationFilenameArrList.get(imageId).imageUrl.equals("")) && (!locationFilenameArrList.get(imageId).imageUrl.equals(null))) {
				imageUrlText = getResources().getText(R.string.downloaded_from).toString() + locationFilenameArrList.get(imageId).imageUrl;
				imageUrl.setText(imageUrlText);
			}
		}

		dialog.setOnDismissListener(new OnDismissListener() {

			public void onDismiss(DialogInterface dialog) {
				// Log.i("onDismissListener", "onDismissListener");
				//myThread.setDrawNext(true);
				g.setRunning(true);
				g.postDelayedScrollNext();
			}

		});

		// set the custom dialog components 
		ImageView iv = (ImageView) dialog.findViewById(R.id.gallery_image);

		iv.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				g.setRunning(true);
				//g.postDelayedScrollNext();
				dialog.dismiss();
				//finish();
			}
		});

		// set background drawable if there is any 
		if (d != null) {
			// Log.i("drawLargeImage", "SetBackgroundDrawable");
			iv.setImageDrawable(d);
			iv.setScaleType(ScaleType.FIT_CENTER);
			iv.setAdjustViewBounds(true);

			//povecava slike
			if (d.getMinimumHeight() <= 280 || d.getMinimumWidth() <= 280) {
				Bitmap bm = ((BitmapDrawable) d).getBitmap();
				int width = bm.getWidth();
				int height = bm.getHeight();
				float scaleWidth = ((float) width * 3) / width;
				float scaleHeight = ((float) height * 3) / height;
				// create a matrix for the manipulation 
				Matrix matrix = new Matrix();
				// resize the bit map 
				matrix.postScale(scaleWidth, scaleHeight);
				// recreate the new Bitmap 
				Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
				BitmapDrawable result = new BitmapDrawable(resizedBitmap);
				iv.setImageDrawable(result);
				iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
				iv.setAdjustViewBounds(true);
			}
			if (d.getMinimumHeight() > 280 && d.getMinimumHeight() < 400 || d.getMinimumWidth() > 280 && d.getMinimumWidth() < 400) {
				Bitmap bm = ((BitmapDrawable) d).getBitmap();
				int width = bm.getWidth();
				int height = bm.getHeight();
				float scaleWidth = ((float) width * 2) / width;
				float scaleHeight = ((float) height * 2) / height;
				// create a matrix for the manipulation 
				Matrix matrix = new Matrix();
				// resize the bit map 
				matrix.postScale(scaleWidth, scaleHeight);
				// recreate the new Bitmap 
				Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
				BitmapDrawable result = new BitmapDrawable(resizedBitmap);
				iv.setImageDrawable(result);
				iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
				iv.setAdjustViewBounds(true);
			}

		}

		dialog.show();

	}

	protected Drawable getDrawableFromPathname(String pathName) {
		Drawable d = null;
		try {
			d = Drawable.createFromStream(getAssets().open(pathName), null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			d = null;
		}
		return d;
	}

	public void showDirectionDialog() {

		// custom dialog
		final Dialog dialog = new Dialog(context);
		dialog.setContentView(R.layout.direction_dialog);
		//dialog.setTitle("City: " + city + ", Location: " + name);

		// set the custom dialog components
		//EditText source = (EditText) dialog.findViewById(R.id.direction_source);
		TextView source = (TextView) dialog.findViewById(R.id.direction_source);
		String srcText = this.getResources().getText(R.string.direction_source).toString();
		srcText += (name + "\r\n" + this.getResources().getText(R.string.direction_destination).toString() + "\r\n");
		source.setText(srcText);

		Button cancelButton = (Button) dialog.findViewById(R.id.cancel_dlg);
		// if button is clicked, close the custom dialog
		cancelButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		Button okButton = (Button) dialog.findViewById(R.id.ok_dlg);
		okButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				EditText dest = (EditText) dialog.findViewById(R.id.direction_destination);
				// Log.i("LocationInfoActivity - showDirectionDialog", "OK button pressed, inserted text:" + dest.getText());
				Intent in = new Intent();
				String destLocation = dest.getText().toString();
				if (destLocation.equals(null) || destLocation.equals("")) 
					setResult(Activity.RESULT_CANCELED, in);
				else {
					in.putExtra("destLocation", dest.getText().toString());
	        		in.putExtra("drawRouteToMyLocation", (int)0);
	        		setResult(Activity.RESULT_OK, in);
					finish();
				}
			}
		});

		Button helpButton = (Button) dialog.findViewById(R.id.help_dlg);

	}

	public Drawable getDrawable(String pathName) {
		Drawable d = null;
		try {
			d = Drawable.createFromStream(getAssets().open(pathName), null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return d;
	}

	/*
	 * public String readFromFile(String pathName) {
	 * 
	 * // int lang = MainActivity.language;
	 * 
	 * // String b = null; // File f = new File(pathName); AssetManager am =
	 * getAssets(); InputStream is = null; try { is = am.open(pathName); } catch
	 * (IOException e1) { // TODO Auto-generated catch block //
	 * e1.printStackTrace(); return this.getString(R.string.na_info); }
	 * 
	 * InputStreamReader inputStream = new InputStreamReader(is);
	 * 
	 * ByteArrayOutputStream byteArrayOutputStream = new
	 * ByteArrayOutputStream();
	 * 
	 * int i; try { i = inputStream.read(); while (i != -1) {
	 * byteArrayOutputStream.write(i); i = inputStream.read(); }
	 * inputStream.close(); } catch (IOException e) { // TODO Auto-generated
	 * catch block e.printStackTrace(); }
	 * 
	 * return byteArrayOutputStream.toString();
	 * 
	 * }
	 */

	public void drawNextImage() {

		if (nextImageId < locationFilenameArrList.size() - 1)
			nextImageId++;
		else
			nextImageId = 0;

		//		galleryFilenameArrList.clear();
		//		if (locationFilenameArrList.size() > 0)
		//			galleryFilenameArrList.add(locationFilenameArrList.get(nextImageId));

	}

	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;
		private Context mContext;

		public ImageAdapter(Context c) {
			mContext = c;

			mContext = c;
			TypedArray a = c.obtainStyledAttributes(R.styleable.DivActGallery);
			mGalleryItemBackground = a.getResourceId(R.styleable.DivActGallery_android_galleryItemBackground, 0);
			a.recycle();

		}

		public int getCount() {
			//return galleryFilenameArrList.size();
			return locationFilenameArrList.size();
		}

		public Object getItem(int position) {
			//return galleryFilenameArrList.get(position);
			return locationFilenameArrList.get(position).imageName;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			ImageView i = new ImageView(mContext);

			Drawable d = null;

			try {
				// Log.i("LocInfoActivity - getView", "Crtamo drawable: " + imagesTumnbails[position]);
				// drawable = Drawable.createFromStream(getAssets().open(imagesTumnbails[position]), null);
				d = Drawable.createFromStream(getAssets().open((String) getItem(position)), null);
				
				if (d.getMinimumHeight() <= 280 || d.getMinimumWidth() <=280) {
					Bitmap bm = ((BitmapDrawable) d).getBitmap();
					int width = bm.getWidth(); 
				    int height = bm.getHeight(); 
				    float scaleWidth = ((float) width*2) / width; 
				    float scaleHeight = ((float) height*2) / height; 
				    // create a matrix for the manipulation 
				    Matrix matrix = new Matrix(); 
				    // resize the bit map 
				    matrix.postScale(scaleWidth, scaleHeight); 
				    // recreate the new Bitmap 
				    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
				    BitmapDrawable result = new BitmapDrawable(resizedBitmap);
//				    iv.setImageDrawable(result);
//					iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
//					iv.setAdjustViewBounds(true);
				    i.setImageDrawable(result);

					i.setScaleType(ImageView.ScaleType.FIT_XY);
					i.setBackgroundResource(mGalleryItemBackground);

					i.setAdjustViewBounds(true);
					i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

					return i;
				}
				
				
				

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			i.setImageDrawable(d);

			i.setScaleType(ImageView.ScaleType.FIT_XY);
			i.setBackgroundResource(mGalleryItemBackground);

			i.setAdjustViewBounds(true);
			i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

			return i;
		}

	}

	public class MyThread extends Thread {
		volatile boolean running = false;
		int cnt;

		void setRunning(boolean b) {
			running = b;
			cnt = 10;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			int position = 0;
			TableLayout tl = (TableLayout) findViewById(R.id.TableLayout1);
			Gallery g = (Gallery) tl.findViewById(R.id.gallery1);
			myAdapter = new ImageAdapter(context);
			g.setAdapter(myAdapter);
			g.setBackgroundColor(Color.TRANSPARENT);

			while (running) {
				try {
					sleep(3000); // wait 2000 miliseconds (not truly accurate)!!!
					//					drawNextImage();

					//myGallery.bringToFront()
					//myGallery.setId(id)

					if (position < myAdapter.getCount()) {
						g.setSelection(position);

						position++;
					} else {
						position--;
						g.setSelection(position);
					}

					handler.sendMessage(handler.obtainMessage());
					/*
					 * if (cnt-- == 0) { running = false;
					 * Log.i("Thread stopped running!!!",
					 * "Thread stopped running"); }
					 */
				} catch (InterruptedException e) {
					e.printStackTrace();

				}
			}

		}

	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			myAdapter.notifyDataSetChanged();
		}

	};

	// Next two overrides are used to stop the thread (for sure) when activity is going ti expire!!!

	@Override
	public void finish() {
		//myThread.setRunning(false);
		//myThread.stop();
		// TODO Auto-generated method stub
		g.setRunning(false);
		super.finish();

	}

	@Override
	public void onBackPressed() {
		//myThread.setRunning(false);
		//myThread.stop();
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
	}

	public class ImageGalleryInfo {
		String imageName;
		String imageUrl;
		
		public ImageGalleryInfo(String imageName, String imageUrl) {
			super();
			this.imageName = imageName;
			this.imageUrl = imageUrl;
		}
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		// return super.onCreateOptionsMenu(menu);
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.locinfo_menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		//return super.onOptionsItemSelected(item);
		switch (item.getItemId()) {

		case R.id.help:
			Intent i = new Intent(context, MainActivity.class);
			if (MainActivity.language == MainActivity.languageEnum.MONTENEGRO.getValue()) 
				i.putExtra("filename", "file:///android_asset/html/OnlineInfo_me.htm");
			else
				i.putExtra("filename", "file:///android_asset/html/OnlineInfo_en.htm");
			context.startActivity(i);
			return true;
			
		default:
			return super.onOptionsItemSelected(item);
		}
		
	}
	
}
